﻿using InterLock.Equipmet;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using static System.Convert;

namespace InterLock.Helper
{
    public class FileReadHelper
    {
        private static readonly string fileName = @"\站场数据.xlsx";

        public static List<Equipment> GetList()
        {
            List<Equipment> listEq = new List<Equipment>();

            IWorkbook wk = null;
            string filePath = Directory.GetCurrentDirectory() + fileName;
            string extension = Path.GetExtension(filePath);
            try
            {
                FileStream fs = File.OpenRead(filePath);
                if (extension.Equals(".xls"))
                {
                    //把xls文件中的数据写入wk中
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    //把xlsx文件中的数据写入wk中
                    wk = new XSSFWorkbook(fs);
                }
                fs.Close();
                ISheet sheet = wk.GetSheetAt(0);
                for (int i = 1; i <= sheet.LastRowNum; i++)       //一行一行读取
                {
                    IRow row = sheet.GetRow(i);

                    int n = ToInt32(row.GetCell(0).ToString(), 16);

                    Equipment s = null;
                    if ((n & ToInt32("0X8000", 16)) != 0)
                    {
                        s = new Track() { N = n, EquipmentType = EquipmentType.Track };
                    }
                    else if ((n & ToInt32("0X2000", 16)) != 0)
                    {
                        s = new Signal() { N = n, EquipmentType = EquipmentType.Signal };
                    }
                    else if ((n & ToInt32("0X4000", 16)) != 0)
                    {
                        s = new Turnout() { N = n, EquipmentType = EquipmentType.Turnout };
                    }
                    s.X1 = int.Parse(row.GetCell(1).ToString());
                    s.Y1 = int.Parse(row.GetCell(2).ToString());
                    s.X2 = int.Parse(row.GetCell(3).ToString());
                    s.Y2 = int.Parse(row.GetCell(4).ToString());
                    s.Name = row.GetCell(5).ToString();
                    s.Character = ToInt32(row.GetCell(6).ToString(), 16);
                    s.LZN = ToInt32(row.GetCell(7).ToString(), 16);
                    s.RZN = ToInt32(row.GetCell(8).ToString(), 16);
                    s.WGN = ToInt32(row.GetCell(9).ToString(), 16);
                    s.JJQ = ToInt32(row.GetCell(10).ToString(), 16);
                    s.FHQ = ToInt32(row.GetCell(11).ToString(), 16);

                    listEq.Add(s);
                }
                return listEq;
            }
            catch
            {
                MessageBox.Show("数据读取错误!", "提示");
                return listEq;
            }
            finally
            {
                wk.Close();
            }
        }
    }
}
